package com.ddxz.shiro.test;

import com.ddxz.tool.core.convert.StringUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.*;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/11/25
 */

public class DdxzRealm extends AuthorizingRealm {
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    /**
     * Retrieves the AuthorizationInfo for the given principals from the underlying data store.  When returning
     * an instance from this method, you might want to consider using an instance of
     * {@link SimpleAuthorizationInfo SimpleAuthorizationInfo}, as it is suitable in most cases.
     *
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return the AuthorizationInfo associated with this principals.
     * @see SimpleAuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if(principals == null || principals.isEmpty()) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        String user = (String) principals.getPrimaryPrincipal();
        List<String> roles = roleList.get(user);
//        Set<String> permissions = new HashSet<>();
        Set<Permission> permissions = new HashSet<>();
//        Permission permission = null;
        roles.forEach(role -> permissionList.get(role).forEach(per -> permissions.add(new DdxzPermission(per))));
//        roles.forEach(role -> permissions.addAll(permissionList.get(role)));
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.setStringPermissions(permissions);
        info.setObjectPermissions(permissions);
        return info;
    }

    /**
     * Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given
     * authentication token.
     * <p/>
     * For most datasources, this means just 'pulling' authentication data for an associated subject/user and nothing
     * more and letting Shiro do the rest.  But in some systems, this method could actually perform EIS specific
     * log-in logic in addition to just retrieving data - it is up to the Realm implementation.
     * <p/>
     * A {@code null} return value means that no account could be associated with the specified token.
     *
     * @param token the authentication token containing the user's principal and credentials.
     * @return an {@link AuthenticationInfo} object containing account data resulting from the
     * authentication ONLY if the lookup is successful (i.e. account exists and is valid, etc.)
     * @throws AuthenticationException if there is an error acquiring data or performing
     *                                 realm-specific authentication logic for the specified <tt>token</tt>
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String password = userList.get(token.getPrincipal());
        if(StringUtil.isEmpty(password)) {
            throw new UnknownAccountException("No account found for user [" + token.getPrincipal() + "]");
        }

        if(!password.equals(StringUtil.join((char[]) token.getCredentials(), ""))) {
            throw new AuthenticationException("account or password error");
        }

        AuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), name);
        return info;
    }

    private static final String name = "DDXZ_REALM";

    private static final Map<String, String> userList = new HashMap<>(5);

    private static final Map<String, List<String>> roleList = new HashMap<>(5);

    private static final Map<String, List<String>> permissionList = new HashMap<>(2);

    static {
        userList.put("admin", "admin@123");
        userList.put("user1", "user1@123");
        userList.put("user2", "user2@123");
        userList.put("user3", "user3@123");
        userList.put("user4", "user4@123");

        roleList.put("admin", Arrays.asList("admin"));
        roleList.put("user1", Arrays.asList("normal", "admin"));
        roleList.put("user2", Arrays.asList("normal"));
        roleList.put("user3", Arrays.asList("normal"));
        roleList.put("user4", Arrays.asList("normal"));

        permissionList.put("admin", Arrays.asList("/path/dir", "/user/**", "/dept/**", "/role/**"));
        permissionList.put("normal", Arrays.asList("/path/dir", "/user/**", "/dept/info", "/dept/list"));
    }
}
